from django.shortcuts import render
from django.http import HttpResponse
import json
from rest_framework.views import APIView
from rest_framework import exceptions
from test1.models import Users

# Create your views here.


class AuthTest1(object):
    def authenticate(self, requests):
        username = requests.GET.get('username')
        passwd = requests.GET.get('passwd')
        if not username or not passwd:
            raise exceptions.AuthenticationFailed('需要用户认证')
        thisUser = Users.objects.filter(username=username, password=passwd)
        if not thisUser:
            raise exceptions.AuthenticationFailed('用户名或密码错误')

    def authenticate_header(self, requests):
        pass


class TestView(APIView):
    authentication_classes = [AuthTest1, ]

    def get(self, requests, *args, **kwargs):
        self.dispatch()
        ret = {
            'code': 10000,
            'msg': 'xxxx'
        }
        print(111)
        return HttpResponse(json.dumps(ret))

    def post(self, requests, *args, **kwargs):
        ret = {
            'code': 10001,
            'msg': '添加'
        }
        return HttpResponse(json.dumps(ret))

    def delete(self, requests, *args, **kwargs):
        ret = {
            'code': 20000,
            'msg': '删除'
        }
        return HttpResponse(json.dumps(ret))

    def put(self, requests, *args, **kwargs):
        ret = {
            'code': 10002,
            'msg': '修改'
        }
        return HttpResponse(json.dumps(ret))

